package com.javafactroy.kunlong.bip.icp.factory;

import com.javafactroy.kunlong.bip.icp.common.consts.IMsgType;
import com.javafactroy.kunlong.bip.icp.factory.iface.IAppMessageFactory;
import com.javafactroy.kunlong.bip.icp.factory.iface.IMessageHandler;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;



public class AppMessageFactory implements IAppMessageFactory {
    private static Map<String, IMessageHandler> mapHandlers = new ConcurrentHashMap<>();
    private static AppMessageFactory inst = new AppMessageFactory();

    private AppMessageFactory() {

    }

    public static AppMessageFactory getInst() {
        return inst;
    }

    @Override
    public void registerHandler(String msgType, IMessageHandler handler) {

        mapHandlers.put(msgType, handler);
    }
    public  static  IMessage execute (IMessage msg) {
        return  inst.executeMsg(msg);
    }

    public   IMessage executeMsg(IMessage msg) {
       return  findHandler(msg.getMsgType()).execute(msg);
    }

    @Override
    public IMessageHandler findHandler(String msgType) {
        IMessageHandler handler = mapHandlers.get(msgType);
        if (handler == null) {
            handler = mapHandlers.get(""+ IMsgType.MsgType_APP_DATA);
        }
        return handler;
    }
}
